package pdf;

import java.io.FileOutputStream;
import java.io.IOException;
import java.io.PrintWriter;

import com.itextpdf.text.DocumentException;
import com.itextpdf.text.pdf.PdfReader;
import com.itextpdf.text.pdf.parser.PdfTextExtractor;

public class GetText 
{
    public static void main(String[] args) throws DocumentException, IOException
    {
        String outputpath = "output/1.txt";//txt文件路径
        PrintWriter writer = new PrintWriter(new FileOutputStream(outputpath));//txt文件写入流 
        String pdffilepath = "resources/demo.pdf";//pdf文件路径 
        inspect(writer,pdffilepath); //调用读取方法 
        writer.close(); 
    }
    public static void inspect(PrintWriter writer, String filename) throws IOException
    {
        try {
            PdfReader reader = new PdfReader(filename); //读取pdf所使用的输出流 
            int PageNum = reader.getNumberOfPages();//获得页数 

            String content = "";  //存放读取出的文档内容 
            for (int i = 1; i <=PageNum; i++)
            {
                content += PdfTextExtractor.getTextFromPage(reader, i);//读取第i页的文档内容 
            } 
            writer.write(content);//写入文件内容 
            writer.flush(); 
        } catch (IOException e) {
            e.printStackTrace();  
        }
     }
}
